from sys import argv
import re
import pycountry
import string

EXAMPLE_URL = "http://chart.apis.google.com/chart?cht=t&chs=350x175&" \
				"chco=f5f5f5,edf0d4,c9dba3,a6c27d,6c9642,365e24,13390a&" \
				"chls=1,4,0&chxt=x&chxl=0:|world&chf=bg,s,EAF7FE&"\
				"chd=s:AEACABAAADABGBAEMABDDBCBCBABAAEAgBABBABBBBVAFCAABBACBECCDABAABDDADBBAAACA9BABECAAFBABBABAA&"\
				"chld=ATSEVEBEESUYALQARSNLCRANPRPHMAMTAUKRCYTTJMARBGAENGDOLVFIEGINNZPKCALUFRDEGRIDSGROOMCHGBPEAWAGJPCOISBBVNDKILLCSIHKHNCZPASKBALYPTGPTRNOBHZAEECLPLKWSAUSBOTHLBVIMUBRECIEMYUAHRMXITBSLTHU"


class GoogleChartError(Exception):
	pass

class GoogleChart(object):
	def __init__(self, url):
		self.url, args = re.match(self.URL_AND_PARAMS_PAT, url).groups()[::2] #Skip the question mark seperating url and params
		self.args = dict(re.findall(self.PARAMS_REGEX, args))
		self.__get_params()
		
	def __get_params(self):
		try:
			self.size = tuple(map(int, self.args[self.PARAM_SIZE].split('x')))
			self.colors = self.args[self.PARAM_SIZE].split(',')
		except KeyError:
			pass
			
	def _parse_data(self, dat):
		ret_data = []
		for dat_serie in dat.split('|'):
			if dat_serie.startswith('s:'):
				ret_data.append(self._decode_simple(dat[2:]))
		
		return ret_data
		
	#DECODERS = {
	#			's': decode_simple
	#			}
		
	def _decode_simple(self, dat):
		return [self.SIMPLE_DECODER[x] for x in dat]
	SIMPLE_ENCODER = list(
						string.ascii_uppercase +
						string.ascii_lowercase +
						string.digits +
						'_') + [None]
	SIMPLE_DECODER = dict(
						zip(
						SIMPLE_ENCODER,
						range(62) + [None]	# Till 61
						)
						)

	URL_AND_PARAMS_PAT = r"(?P<url>http://chart\.apis\.google\.com/chart)(\?)(?P<params>\S*)"
	PARAMS_REGEX = r"(?P<name>[a-zA-Z]{1}[a-zA-Z0-9]*?)=(?P<value>\S+?(?=&|$))"
	
	PARAM_TYPE = 'cht'
	PARAM_SIZE = 'chs'
	PARAM_COLORS = 'chco'

class MapChart(GoogleChart):
	def __init__(self, url):
		GoogleChart.__init__(self, url)
		try:
			if self.args[self.PARAM_TYPE] != 't':
				raise KeyError
			self.__get_params()
		except KeyError:
			raise GoogleChartError, "Wrong Parameters"
	
	def __get_params(self):
		pass
			
	def get_countries(self):
		countries = self.args[self.PARAM_COUNTRIES]
		clevels = self.args[self.PARAM_COLOR_LEVELS]
		
		lst_countries = map(lambda x: countries[x:x+2], range(0, len(countries), 2))
		#print lst_countries
		clevels_numeric = self._parse_data(clevels)[0]
		#print clevels_numeric
		return dict(zip(lst_countries, clevels_numeric))
		
	PARAM_COUNTRIES = 'chld'
	PARAM_COLOR_LEVELS = 'chd'
	
	GEO_AFRICA = 'africa'
	GEO_ASIA = 'asia'
	GEO_EUROPE = 'europe'
	GEO_ME = 'middle_east'
	GEO_SOUTH_AMERICA = 'south_america'
	GEO_USA = 'usa'
	GEO_WORLD = 'world'
	
def main():
	gc = MapChart(EXAMPLE_URL)
	#print gc.SIMPLE_DECODER
	#print gc.size
	print gc.get_countries()
	
if "__main__" == __name__:
	main()